
/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2022原作者。
 *
 *根据Apache许可证2.0版许可（“许可证”）；
 *除非符合许可证的规定，否则您不得使用此文件。
 *您可以在以下网址获取许可证副本：
 *
 *https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证进行的分发是在“按原样”的基础上进行的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限的特定语言，请参阅许可证和
 *许可证下的限制。
 */

package org.springframework.scripting.support;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
import org.springframework.asm.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionValidationException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.proxy.InterfaceMaker;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.Conventions;
import org.springframework.core.Ordered;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} that
 * handles {@link org.springframework.scripting.ScriptFactory} definitions,
 * replacing each factory with the actual scripted Java object generated by it.
 *
 * <p>This is similar to the
 * {@link org.springframework.beans.factory.FactoryBean} mechanism, but is
 * specifically tailored for scripts and not built into Spring's core
 * container itself but rather implemented as an extension.
 *
 * <p><b>NOTE:</b> The most important characteristic of this post-processor
 * is that constructor arguments are applied to the
 * {@link org.springframework.scripting.ScriptFactory} instance
 * while bean property values are applied to the generated scripted object.
 * Typically, constructor arguments include a script source locator and
 * potentially script interfaces, while bean property values include
 * references and config values to inject into the scripted object itself.
 *
 * <p>The following {@link ScriptFactoryPostProcessor} will automatically
 * be applied to the two
 * {@link org.springframework.scripting.ScriptFactory} definitions below.
 * At runtime, the actual scripted objects will be exposed for
 * "bshMessenger" and "groovyMessenger", rather than the
 * {@link org.springframework.scripting.ScriptFactory} instances. Both of
 * those are supposed to be castable to the example's {@code Messenger}
 * interfaces here.
 *
 * <pre class="code">&lt;bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/&gt;
 *
 * &lt;bean id="bshMessenger" class="org.springframework.scripting.bsh.BshScriptFactory"&gt;
 *   &lt;constructor-arg value="classpath:mypackage/Messenger.bsh"/&gt;
 *   &lt;constructor-arg value="mypackage.Messenger"/&gt;
 *   &lt;property name="message" value="Hello World!"/&gt;
 * &lt;/bean&gt;
 *
 * &lt;bean id="groovyMessenger" class="org.springframework.scripting.groovy.GroovyScriptFactory"&gt;
 *   &lt;constructor-arg value="classpath:mypackage/Messenger.groovy"/&gt;
 *   &lt;property name="message" value="Hello World!"/&gt;
 * &lt;/bean&gt;</pre>
 *
 * <p><b>NOTE:</b> Please note that the above excerpt from a Spring
 * XML bean definition file uses just the &lt;bean/&gt;-style syntax
 * (in an effort to illustrate using the {@link ScriptFactoryPostProcessor} itself).
 * In reality, you would never create a &lt;bean/&gt; definition for a
 * {@link ScriptFactoryPostProcessor} explicitly; rather you would import the
 * tags from the {@code 'lang'} namespace and simply create scripted
 * beans using the tags in that namespace... as part of doing so, a
 * {@link ScriptFactoryPostProcessor} will implicitly be created for you.
 *
 * <p>The Spring reference documentation contains numerous examples of using
 * tags in the {@code 'lang'} namespace; by way of an example, find below
 * a Groovy-backed bean defined using the {@code 'lang:groovy'} tag.
 *
 * <pre class="code">
 * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 * &lt;beans xmlns="http://www.springframework.org/schema/beans"
 *     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *     xmlns:lang="http://www.springframework.org/schema/lang"&gt;
 *
 *   &lt;!-- this is the bean definition for the Groovy-backed Messenger implementation --&gt;
 *   &lt;lang:groovy id="messenger" script-source="classpath:Messenger.groovy"&gt;
 *     &lt;lang:property name="message" value="I Can Do The Frug" /&gt;
 *   &lt;/lang:groovy&gt;
 *
 *   &lt;!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger --&gt;
 *   &lt;bean id="bookingService" class="x.y.DefaultBookingService"&gt;
 *     &lt;property name="messenger" ref="messenger" /&gt;
 *   &lt;/bean&gt;
 *
 * &lt;/beans&gt;</pre>
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rick Evans
 * @author Mark Fisher
 * @author Sam Brannen
 * @since 2.0
 */
/**
 *｛@linkorg.springframework.beans.factory.config.BeanPostProcessor｝
 *处理{@linkorg.springframework.scripting.ScriptFactory}定义，
 *用它生成的实际脚本化Java对象替换每个工厂。
 *
 *<p>这与
 *{@linkorg.springframework.beans.factory.FactoryBean}机制，但是是
 *专门为脚本量身定制，而不是内置在Spring的核心中
 *容器本身，而是作为扩展实现。
 *
 *<p><b>注意：</b>此后处理器最重要的特性
 *构造函数参数应用于
 *｛@linkorg.springframework.scripting.ScriptFactory｝实例
 *而bean属性值被应用于生成的脚本对象。
 *通常，构造函数参数包括脚本源定位器和
 *潜在的脚本接口，而bean属性值包括
 *引用和配置值，以注入到脚本对象本身中。
 *
 *<p>以下｛@link ScriptFactoryPostProcessor｝将自动
 *应用于两者
 *｛@linkorg.springframework.scripting.ScriptFactory｝定义如下。
 *在运行时，实际的脚本化对象将为
 *“bshMessenger”和“groovyMessenger”，而不是
 *｛@linkorg.springframework.scripting.ScriptFactory｝个实例。两者
 *这些应该可以投射到示例的｛@code Messenger｝中
 *此处的接口。
 *
 *<pre-class=“code”>&lt；bean class=“org.springframework.scripting.support.ScriptFactoryPostProcessor”/&gt；
 *
 *&lt；bean id=“bshMessenger”class=“org.springframework.scripting.bsh.BshScriptFactory”&gt；
 *&lt；构造函数arg value=“classpath：mypackage/Messenger.bsh”/&gt；
 *&lt；构造函数arg value=“mypackage.Messenger”/&gt；
 *&lt；property name=“message”value=“你好，世界！”/&gt；
 *&lt/豆&gt；
 *
 *&lt；bean id=“groovyMessenger”class=“org.springframework.scripting.groovy.GroovyScriptFactory”&gt；
 *&lt；构造函数arg value=“classpath：mypackage/Messenger.groovy”/&gt；
 *&lt；property name=“message”value=“你好，世界！”/&gt；
 *&lt/豆&gt</预>
 *
 *<p><b>注意：</b>请注意，以上摘录自Spring
 *XML bean定义文件仅使用&lt；豆/&gt-样式语法
 *（为了说明使用{@linkScriptFactoryPostProcessor}本身）。
 *事实上，你永远不会创建一个&lt；豆/&gt；的定义
 *｛@link ScriptFactoryPostProcessor｝显式；你宁愿进口
 *标记，并简单地创建脚本
 *使用该名称空间中的标记的bean。。。作为这样做的一部分
 *｛@link ScriptFactoryPostProcessor｝将隐式为您创建。
 *
 *＜p＞Spring参考文档包含许多使用
 *｛@code'lang'｝命名空间中的标记；举个例子，如下所示
 *使用{@code'lang:Groovy'}标记定义的Groovy支持的bean。
 *
 *<pre-class=“code”>
 *&lt；？xml版本=“1.0”编码=“UTF-8”&gt；
 *&lt；beans xmlns=“http://www.springframework.org/schema/beans”
 *xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
 *xmlns:lang=“http://www.springframework.org/schema/lang“&gt；
 *
 *&lt；！——这是Groovy支持的Messenger实现的bean定义--&gt；
 *&lt；lang:groovy id=“messenger”script source=“classpath:messenger.groovy”&gt；
 *&lt；lang:property name=“message”value=“I Can Do The Frug”/&gt；
 *&lt/lang:groovy&gt；
 *
 *&lt；！——将由Groovy支持的Messenger注入的正常bean--&gt；
 *&lt；bean id=“bookingService”class=“x.y.DefaultBookingService”&gt；
 *&lt；property name=“messenger”ref=“messener”/&gt；
 *&lt/豆&gt；
 *
 *&lt/豆子&gt</预>
 *
 *@作者于尔根·霍勒
 *@作者Rob Harrop
 *@作者Rick Evans
 *@作者Mark Fisher
 *@作者Sam Brannen
 *@自2.0起
 */
public class ScriptFactoryPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
		BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware, DisposableBean, Ordered {

	/**
	 * The {@link org.springframework.core.io.Resource}-style prefix that denotes
	 * an inline script.
	 * <p>An inline script is a script that is defined right there in the (typically XML)
	 * configuration, as opposed to being defined in an external file.
	 */
	/**
	 *{@linkorg.springframework.core.io.Resource}风格的前缀，表示
	 *内联脚本。
	 *＜p＞内联脚本是在（通常是XML）中直接定义的脚本
	 *配置，而不是在外部文件中定义。
	 */
	public static final String INLINE_SCRIPT_PREFIX = "inline:";

	/**
	 * The {@code refreshCheckDelay} attribute.
	 */
	/**
	 *｛@code refreshCheckDelay｝属性。
	 */
	public static final String REFRESH_CHECK_DELAY_ATTRIBUTE = Conventions.getQualifiedAttributeName(
			ScriptFactoryPostProcessor.class, "refreshCheckDelay");

	/**
	 * The {@code proxyTargetClass} attribute.
	 */
	/**
	 *｛@code proxyTargetClass｝属性。
	 */
	public static final String PROXY_TARGET_CLASS_ATTRIBUTE = Conventions.getQualifiedAttributeName(
			ScriptFactoryPostProcessor.class, "proxyTargetClass");

	/**
	 * The {@code language} attribute.
	 */
	/**
	 *｛@code language｝属性。
	 */
	public static final String LANGUAGE_ATTRIBUTE = Conventions.getQualifiedAttributeName(
			ScriptFactoryPostProcessor.class, "language");

	private static final String SCRIPT_FACTORY_NAME_PREFIX = "scriptFactory.";

	private static final String SCRIPTED_OBJECT_NAME_PREFIX = "scriptedObject.";


	/** Logger available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());

	private long defaultRefreshCheckDelay = -1;

	private boolean defaultProxyTargetClass = false;

	@Nullable
	private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

	@Nullable
	private ConfigurableBeanFactory beanFactory;

	private ResourceLoader resourceLoader = new DefaultResourceLoader();

	final DefaultListableBeanFactory scriptBeanFactory = new DefaultListableBeanFactory();

	/** Map from bean name String to ScriptSource object. */
	private final Map<String, ScriptSource> scriptSourceCache = new ConcurrentHashMap<>();


	/**
	 * Set the delay between refresh checks, in milliseconds.
	 * Default is -1, indicating no refresh checks at all.
	 * <p>Note that an actual refresh will only happen when
	 * the {@link org.springframework.scripting.ScriptSource} indicates
	 * that it has been modified.
	 * @see org.springframework.scripting.ScriptSource#isModified()
	 */
	/** Logger available to subclasses. */
	protected最终日志记录器=LogFactory.getLog（getClass（））；

	private long defaultRefreshCheckDelay=-1；

	private布尔值defaultProxyTargetClass=false；

	@可为null
	private ClassLoader beanClassLoader=ClassUtils.getDefaultClassLoader（）；

	@可为null
	私有可配置beanFactory beanFactory；

	private ResourceLoader ResourceLoader=新的DefaultResourceLoader（）；

	final DefaultListableBeanFactory scriptBeanFactory=新的DefaultListableBeanFactory（）；

	/**从bean名称String映射到ScriptSource对象*/
	private final Map＜String，ScriptSource＞scriptSourceCache＝new ConcurrentHashMap＜＞（）；


	/**
	 *设置刷新检查之间的延迟（以毫秒为单位）。
	 *默认值为-1，表示根本没有刷新检查。
	 *<p>请注意，只有当
	 *｛@linkorg.springframework.scripting.ScriptSource｝表示
	 *它已被修改。
	 *@参见org.springframework.scripting.ScriptSource#isModified（）
	 */
	public void setDefaultRefreshCheckDelay(long defaultRefreshCheckDelay) {
		this.defaultRefreshCheckDelay = defaultRefreshCheckDelay;
	}

	/**
	 * Flag to signal that refreshable proxies should be created to proxy the target class not its interfaces.
	 * @param defaultProxyTargetClass the flag value to set
	 */
	/**
	 *标志，表示应创建可刷新代理来代理目标类而不是其接口。
	 *@param defaultProxyTargetClass要设置的标志值
	 */
	public void setDefaultProxyTargetClass(boolean defaultProxyTargetClass) {
		this.defaultProxyTargetClass = defaultProxyTargetClass;
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.beanClassLoader = classLoader;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		if (!(beanFactory instanceof ConfigurableBeanFactory)) {
			throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with " +
					"non-ConfigurableBeanFactory: " + beanFactory.getClass());
		}
		this.beanFactory = (ConfigurableBeanFactory) beanFactory;

		// Required so that references (up container hierarchies) are correctly resolved.
		// 必需，以便正确解析引用（向上容器层次结构）。
		this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

		// Required so that all BeanPostProcessors, Scopes, etc become available.
		// 必需，以便所有BeanPostProcessors、Scopes等都可用。
		this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

		// Filter out BeanPostProcessors that are part of the AOP infrastructure,
		// 过滤掉作为AOP基础设施的一部分的BeanPostProcessors，
		// since those are only meant to apply to beans defined in the original factory.
		// 因为这些仅适用于在原始工厂中定义的bean。
		this.scriptBeanFactory.getBeanPostProcessors().removeIf(beanPostProcessor ->
				beanPostProcessor instanceof AopInfrastructureBean);
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE;
	}


	@Override
	@Nullable
	public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
		// We only apply special treatment to ScriptFactory implementations here.
		// 我们在这里只对ScriptFactory实现进行特殊处理。
		if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
			return null;
		}

		Assert.state(this.beanFactory != null, "No BeanFactory set");
		BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);

		try {
			String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
			String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
			prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);

			ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
			ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
			Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

			Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
			if (scriptedType != null) {
				return scriptedType;
			}
			else if (!ObjectUtils.isEmpty(interfaces)) {
				return (interfaces.length == 1 ? interfaces[0] : createCompositeInterface(interfaces));
			}
			else {
				if (bd.isSingleton()) {
					return this.scriptBeanFactory.getBean(scriptedObjectBeanName).getClass();
				}
			}
		}
		catch (Exception ex) {
			if (ex instanceof BeanCreationException &&
					((BeanCreationException) ex).getMostSpecificCause() instanceof BeanCurrentlyInCreationException) {
				if (logger.isTraceEnabled()) {
					logger.trace("Could not determine scripted object type for bean '" + beanName + "': " +
							ex.getMessage());
				}
			}
			else {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not determine scripted object type for bean '" + beanName + "'", ex);
				}
			}
		}

		return null;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		return pvs;
	}

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
		// We only apply special treatment to ScriptFactory implementations here.
		// 我们在这里只对ScriptFactory实现进行特殊处理。
		if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
			return null;
		}

		Assert.state(this.beanFactory != null, "No BeanFactory set");
		BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
		String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
		String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
		prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);

		ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
		ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
		boolean isFactoryBean = false;
		try {
			Class<?> scriptedObjectType = scriptFactory.getScriptedObjectType(scriptSource);
			// Returned type may be null if the factory is unable to determine the type.
			// 如果工厂无法确定返回的类型，则返回的类型可能为null。
			if (scriptedObjectType != null) {
				isFactoryBean = FactoryBean.class.isAssignableFrom(scriptedObjectType);
			}
		}
		catch (Exception ex) {
			throw new BeanCreationException(beanName,
					"Could not determine scripted object type for " + scriptFactory, ex);
		}

		long refreshCheckDelay = resolveRefreshCheckDelay(bd);
		if (refreshCheckDelay >= 0) {
			Class<?>[] interfaces = scriptFactory.getScriptInterfaces();
			RefreshableScriptTargetSource ts = new RefreshableScriptTargetSource(this.scriptBeanFactory,
					scriptedObjectBeanName, scriptFactory, scriptSource, isFactoryBean);
			boolean proxyTargetClass = resolveProxyTargetClass(bd);
			String language = (String) bd.getAttribute(LANGUAGE_ATTRIBUTE);
			if (proxyTargetClass && (language == null || !language.equals("groovy"))) {
				throw new BeanDefinitionValidationException(
						"Cannot use proxyTargetClass=true with script beans where language is not 'groovy': '" +
						language + "'");
			}
			ts.setRefreshCheckDelay(refreshCheckDelay);
			return createRefreshableProxy(ts, interfaces, proxyTargetClass);
		}

		if (isFactoryBean) {
			scriptedObjectBeanName = BeanFactory.FACTORY_BEAN_PREFIX + scriptedObjectBeanName;
		}
		return this.scriptBeanFactory.getBean(scriptedObjectBeanName);
	}

	/**
	 * Prepare the script beans in the internal BeanFactory that this
	 * post-processor uses. Each original bean definition will be split
	 * into a ScriptFactory definition and a scripted object definition.
	 * @param bd the original bean definition in the main BeanFactory
	 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
	 * @param scriptedObjectBeanName the name of the internal scripted object bean
	 */
	/**
	 *在内部BeanFactory中准备脚本bean
	 *后处理器使用。每个原始bean定义都将被拆分
	 *分为ScriptFactory定义和脚本化对象定义。
	 *@param bd主BeanFactory中的原始bean定义
	 *@param scriptFactoryBean命名内部ScriptFactory bean的名称
	 *@param scriptedObjectBeanName内部脚本化对象bean的名称
	 */
	protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanName, String scriptedObjectBeanName) {
		// Avoid recreation of the script bean definition in case of a prototype.
		// 在原型的情况下，避免重新创建脚本bean定义。
		synchronized (this.scriptBeanFactory) {
			if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {

				this.scriptBeanFactory.registerBeanDefinition(
						scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
				ScriptFactory scriptFactory =
						this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
				ScriptSource scriptSource =
						getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
				Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

				Class<?>[] scriptedInterfaces = interfaces;
				if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) {
					Class<?> configInterface = createConfigInterface(bd, interfaces);
					scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface);
				}

				BeanDefinition objectBd = createScriptedObjectBeanDefinition(
						bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
				long refreshCheckDelay = resolveRefreshCheckDelay(bd);
				if (refreshCheckDelay >= 0) {
					objectBd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
				}

				this.scriptBeanFactory.registerBeanDefinition(scriptedObjectBeanName, objectBd);
			}
		}
	}

	/**
	 * Get the refresh check delay for the given {@link ScriptFactory} {@link BeanDefinition}.
	 * If the {@link BeanDefinition} has a
	 * {@link org.springframework.core.AttributeAccessor metadata attribute}
	 * under the key {@link #REFRESH_CHECK_DELAY_ATTRIBUTE} which is a valid {@link Number}
	 * type, then this value is used. Otherwise, the {@link #defaultRefreshCheckDelay}
	 * value is used.
	 * @param beanDefinition the BeanDefinition to check
	 * @return the refresh check delay
	 */
	/**
	 *获取给定｛@link ScriptFactory｝｛@linkBeanDefinition｝的刷新检查延迟。
	 *如果｛@link BeanDefinition｝具有
	 *｛@link org.springframework.core.AttributeAccessor元数据属性｝
	 *在密钥｛@link#REFRESH_CHECK_DELAY_ATTRIBUTE｝下，该密钥是有效的｛@link编号｝
	 *类型，则使用此值。否则，｛@link#defaultRefreshCheckDelay｝
	 *值。
	 *@param beanDefinition要检查的beanDefinition
	 *@返回刷新检查延迟
	 */
	protected long resolveRefreshCheckDelay(BeanDefinition beanDefinition) {
		long refreshCheckDelay = this.defaultRefreshCheckDelay;
		Object attributeValue = beanDefinition.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
		if (attributeValue instanceof Number) {
			refreshCheckDelay = ((Number) attributeValue).longValue();
		}
		else if (attributeValue instanceof String) {
			refreshCheckDelay = Long.parseLong((String) attributeValue);
		}
		else if (attributeValue != null) {
			throw new BeanDefinitionStoreException("Invalid refresh check delay attribute [" +
					REFRESH_CHECK_DELAY_ATTRIBUTE + "] with value '" + attributeValue +
					"': needs to be of type Number or String");
		}
		return refreshCheckDelay;
	}

	protected boolean resolveProxyTargetClass(BeanDefinition beanDefinition) {
		boolean proxyTargetClass = this.defaultProxyTargetClass;
		Object attributeValue = beanDefinition.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
		if (attributeValue instanceof Boolean) {
			proxyTargetClass = (Boolean) attributeValue;
		}
		else if (attributeValue instanceof String) {
			proxyTargetClass = Boolean.parseBoolean((String) attributeValue);
		}
		else if (attributeValue != null) {
			throw new BeanDefinitionStoreException("Invalid proxy target class attribute [" +
					PROXY_TARGET_CLASS_ATTRIBUTE + "] with value '" + attributeValue +
					"': needs to be of type Boolean or String");
		}
		return proxyTargetClass;
	}

	/**
	 * Create a ScriptFactory bean definition based on the given script definition,
	 * extracting only the definition data that is relevant for the ScriptFactory
	 * (that is, only bean class and constructor arguments).
	 * @param bd the full script bean definition
	 * @return the extracted ScriptFactory bean definition
	 * @see org.springframework.scripting.ScriptFactory
	 */
	/**
	 *基于给定的脚本定义创建ScriptFactory bean定义，
	 *仅提取与ScriptFactory相关的定义数据
	 *（也就是说，只有bean类和构造函数参数）。
	 *@param bd完整的脚本bean定义
	 *@return提取的ScriptFactory bean定义
	 *@参见org.springframework.scripting.ScriptFactory
	 */
	protected BeanDefinition createScriptFactoryBeanDefinition(BeanDefinition bd) {
		GenericBeanDefinition scriptBd = new GenericBeanDefinition();
		scriptBd.setBeanClassName(bd.getBeanClassName());
		scriptBd.getConstructorArgumentValues().addArgumentValues(bd.getConstructorArgumentValues());
		return scriptBd;
	}

	/**
	 * Obtain a ScriptSource for the given bean, lazily creating it
	 * if not cached already.
	 * @param beanName the name of the scripted bean
	 * @param scriptSourceLocator the script source locator associated with the bean
	 * @return the corresponding ScriptSource instance
	 * @see #convertToScriptSource
	 */
	/**
	 *获取给定bean的ScriptSource，然后惰性地创建它
	 *如果尚未缓存。
	 *@param beanName脚本化bean的名称
	 *@param scriptSourceLocator与bean关联的脚本源定位器
	 *@返回对应的ScriptSource实例
	 *@参见#convertToScriptSource
	 */
	protected ScriptSource getScriptSource(String beanName, String scriptSourceLocator) {
		return this.scriptSourceCache.computeIfAbsent(beanName, key ->
				convertToScriptSource(beanName, scriptSourceLocator, this.resourceLoader));
	}

	/**
	 * Convert the given script source locator to a ScriptSource instance.
	 * <p>By default, supported locators are Spring resource locations
	 * (such as "file:C:/myScript.bsh" or "classpath:myPackage/myScript.bsh")
	 * and inline scripts ("inline:myScriptText...").
	 * @param beanName the name of the scripted bean
	 * @param scriptSourceLocator the script source locator
	 * @param resourceLoader the ResourceLoader to use (if necessary)
	 * @return the ScriptSource instance
	 */
	/**
	 *将给定的脚本源定位器转换为ScriptSource实例。
	 *<p>默认情况下，支持的定位器是Spring资源位置
	 *（例如“file:C:/myScript.bsh”或“classpath：myPackage/myScript.bsh”）
	 *和内联脚本（“inline:myScriptText…”）。
	 *@param beanName脚本化bean的名称
	 *@param scriptSourceLocator脚本源定位器
	 *@param resourceLoader要使用的resourceLoader（如有必要）
	 *@返回ScriptSource实例
	 */
	protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator,
			ResourceLoader resourceLoader) {

		if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
			return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
		}
		else {
			return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
		}
	}

	/**
	 * Create a config interface for the given bean definition, defining setter
	 * methods for the defined property values as well as an init method and
	 * a destroy method (if defined).
	 * <p>This implementation creates the interface via CGLIB's InterfaceMaker,
	 * determining the property types from the given interfaces (as far as possible).
	 * @param bd the bean definition (property values etc) to create a
	 * config interface for
	 * @param interfaces the interfaces to check against (might define
	 * getters corresponding to the setters we're supposed to generate)
	 * @return the config interface
	 * @see org.springframework.cglib.proxy.InterfaceMaker
	 * @see org.springframework.beans.BeanUtils#findPropertyType
	 */
	/**
	 *为给定的bean定义创建一个配置接口，定义setter
	 *方法，以及init方法和
	 *销毁方法（如果已定义）。
	 *<p>此实现通过CGLIB的InterfaceMaker创建接口，
	 *根据给定接口（尽可能）确定属性类型。
	 *@param-bd用于创建
	 *的配置接口
	 *@param interfaces要检查的接口（可能定义
	 *getter对应于我们应该生成的setter）
	 *@返回配置界面
	 *@参见org.springframework.cglib.proxy.InterfaceMaker
	 *@见org.springframework.beans.BeanUtils#findPropertyType
	 */
	protected Class<?> createConfigInterface(BeanDefinition bd, @Nullable Class<?>[] interfaces) {
		InterfaceMaker maker = new InterfaceMaker();
		PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
		for (PropertyValue pv : pvs) {
			String propertyName = pv.getName();
			Class<?> propertyType = BeanUtils.findPropertyType(propertyName, interfaces);
			String setterName = "set" + StringUtils.capitalize(propertyName);
			Signature signature = new Signature(setterName, Type.VOID_TYPE, new Type[] {Type.getType(propertyType)});
			maker.add(signature, new Type[0]);
		}
		if (StringUtils.hasText(bd.getInitMethodName())) {
			Signature signature = new Signature(bd.getInitMethodName(), Type.VOID_TYPE, new Type[0]);
			maker.add(signature, new Type[0]);
		}
		if (StringUtils.hasText(bd.getDestroyMethodName())) {
			Signature signature = new Signature(bd.getDestroyMethodName(), Type.VOID_TYPE, new Type[0]);
			maker.add(signature, new Type[0]);
		}
		return maker.create();
	}

	/**
	 * Create a composite interface Class for the given interfaces,
	 * implementing the given interfaces in one single Class.
	 * <p>The default implementation builds a JDK proxy class
	 * for the given interfaces.
	 * @param interfaces the interfaces to merge
	 * @return the merged interface as Class
	 * @see java.lang.reflect.Proxy#getProxyClass
	 */
	/**
	 *为给定的接口创建一个复合接口类，
	 *在一个类中实现给定的接口。
	 *＜p＞默认实现构建JDK代理类
	 *对于给定的接口。
	 *@param接口要合并的接口
	 *@将合并后的接口返回为Class
	 *@参见java.lang.reflect.Proxy#getProxyClass
	 */
	protected Class<?> createCompositeInterface(Class<?>[] interfaces) {
		return ClassUtils.createCompositeInterface(interfaces, this.beanClassLoader);
	}

	/**
	 * Create a bean definition for the scripted object, based on the given script
	 * definition, extracting the definition data that is relevant for the scripted
	 * object (that is, everything but bean class and constructor arguments).
	 * @param bd the full script bean definition
	 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
	 * @param scriptSource the ScriptSource for the scripted bean
	 * @param interfaces the interfaces that the scripted bean is supposed to implement
	 * @return the extracted ScriptFactory bean definition
	 * @see org.springframework.scripting.ScriptFactory#getScriptedObject
	 */
	/**
	 *根据给定的脚本为脚本对象创建一个bean定义
	 *定义，提取与脚本相关的定义数据
	 *对象（即除了bean类和构造函数参数之外的所有参数）。
	 *@param bd完整的脚本bean定义
	 *@param scriptFactoryBean命名内部ScriptFactory bean的名称
	 
	 *@param接口脚本化bean应该实现的接口
	 *@return提取的ScriptFactory bean定义
	 *@参见org.springframework.scripting.ScriptFactory#getScriptedObject
	 */
	protected BeanDefinition createScriptedObjectBeanDefinition(BeanDefinition bd, String scriptFactoryBeanName,
			ScriptSource scriptSource, @Nullable Class<?>[] interfaces) {

		GenericBeanDefinition objectBd = new GenericBeanDefinition(bd);
		objectBd.setFactoryBeanName(scriptFactoryBeanName);
		objectBd.setFactoryMethodName("getScriptedObject");
		objectBd.getConstructorArgumentValues().clear();
		objectBd.getConstructorArgumentValues().addIndexedArgumentValue(0, scriptSource);
		objectBd.getConstructorArgumentValues().addIndexedArgumentValue(1, interfaces);
		return objectBd;
	}

	/**
	 * Create a refreshable proxy for the given AOP TargetSource.
	 * @param ts the refreshable TargetSource
	 * @param interfaces the proxy interfaces (may be {@code null} to
	 * indicate proxying of all interfaces implemented by the target class)
	 * @return the generated proxy
	 * @see RefreshableScriptTargetSource
	 */
	/**
	 *为给定的AOP TargetSource创建一个可刷新的代理。
	 *@param ts可刷新的TargetSource
	 *@param接口代理接口（可以是｛@code null｝到
	 *指示由目标类实现的所有接口的代理）
	 *@返回生成的代理
	 *@请参阅RefreshableScriptTargetSource
	 */
	protected Object createRefreshableProxy(TargetSource ts, @Nullable Class<?>[] interfaces, boolean proxyTargetClass) {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTargetSource(ts);
		ClassLoader classLoader = this.beanClassLoader;

		if (interfaces != null) {
			proxyFactory.setInterfaces(interfaces);
		}
		else {
			Class<?> targetClass = ts.getTargetClass();
			if (targetClass != null) {
				proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.beanClassLoader));
			}
		}

		if (proxyTargetClass) {
			classLoader = null;  // force use of Class.getClassLoader()
			proxyFactory.setProxyTargetClass(true);
		}

		DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
		introduction.suppressInterface(TargetSource.class);
		proxyFactory.addAdvice(introduction);

		return proxyFactory.getProxy(classLoader);
	}

	/**
	 * Destroy the inner bean factory (used for scripts) on shutdown.
	 */
	/**
	 *关闭时销毁内部bean工厂（用于脚本）。
	 */
	@Override
	public void destroy() {
		this.scriptBeanFactory.destroySingletons();
	}

}
